package com.xiaoma.tpo.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.stereotype.Repository;

import com.xiaoma.tpo.baseDao.BaseDaoImpl;
import com.xiaoma.tpo.baseDao.DefaultRowMapper;
import com.xiaoma.tpo.domain.ClsScore;
import com.xiaoma.tpo.dto.ClsGateScoreDto;

@Repository
public class ClsScoreDao extends BaseDaoImpl<ClsScore>{

    
    private static final Logger LOG = LoggerFactory.getLogger(ClsScoreDao.class);
    @SuppressWarnings("unchecked")
    public List<ClsGateScoreDto> findScoresByClassIdAndUserId(int classId, int userId) {
        String sql = "select cls_course_id course_id, cls_gate_id gate_id, score from cls_score where cls_class_id = ? and user_id = ? order by cls_course_id, cls_gate_id asc";
        LOG.info("SQL:{}; classId:{}; userId:{}", sql, classId, userId);
        List<?> result = jdbcTemplate.query(sql, new DefaultRowMapper(ClsGateScoreDto.class, getNameHandler()), classId, userId);
        return (List<ClsGateScoreDto>)result;
    }
    
    @SuppressWarnings("unchecked")
    public List<Integer> findPrizeCourse(int classId, int userId) {
        String sql = "select cls_course_id from cls_score where score >= 90 and user_id = ? and cls_class_id = ? group by cls_course_id having count(*) >= 3";
        LOG.info("SQL:{}; userId:{}; classId:{}", sql, userId, classId);
//        List<?> result = jdbcTemplate.query(sql, new DefaultRowMapper(Integer.class, getNameHandler()), userId, classId);
        List<?> result = jdbcTemplate.query(sql, new Object[]{userId, classId},new ResultSetExtractor(){

            @Override
            public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
                // TODO Auto-generated method stub
                List<Integer> ids = new ArrayList<Integer>();
                while (rs.next()) {
                    ids.add(rs.getInt("cls_course_id"));
                }
                return ids;
            }
            
        });
        return (List<Integer>)result;
    }
    
//    public boolean finished(int classId, int userId) {
//        String sql = "select count(*) from cls_score where cls_class_id = ? and user_id = ?";
//        LOG.info("SQL:{}; classId:{}; userId:{}", sql, classId, userId);
//        int count = jdbcTemplate.queryForInt(sql,classId, userId);
//        return count == 63;//21 * 3
//    }
}
